
package com.smartfactory.sail.controller;

import com.ada.base.common.ApiResponse;
import com.ada.base.common.ControllerResponse;
import com.smartfactory.sail.service.IFileService;
import com.smartfactory.sail.utils.CodeUtils;
import com.smartfactory.sail.utils.ZXingCode;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.tomcat.util.http.fileupload.IOUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.awt.image.BufferedImage;
import java.io.*;
import java.util.UUID;

/**
 * 文件上传下载
 */
@Api(tags = "文件上传下载")
@RestController
public class FileController extends ControllerResponse {
    private static final Logger log = LoggerFactory.getLogger(FileController.class);

    @Value("${filePath}")
    private String FILEPATH;

    private IFileService iFileService;

    public FileController(IFileService iFileService) {
        this.iFileService = iFileService;
    }

    @ApiOperation(value = "文件上传", notes = "文件上传")
    @PostMapping(value = "/upload")
    public ApiResponse<Long> upload(@RequestParam("file") MultipartFile file) {
        try {
            if (file.isEmpty()) {
                return fail("文件为空");
            }
            // 获取文件名
            String fileName = CodeUtils.getCode() + "_" + UUID.randomUUID() + file
                    .getOriginalFilename().substring(file
                            .getOriginalFilename().lastIndexOf("."));
            log.info("上传的文件名为：" + fileName);
            File dest = new File(FILEPATH + fileName);
            file.transferTo(dest);// 文件写入
            com.smartfactory.sail.entity.File dbFile = new com.smartfactory.sail.entity.File();
            dbFile.setFileName(fileName);
            if (iFileService.save(dbFile)) {
                return ok(dbFile.getId());
            }
        } catch (IllegalStateException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
        return fail("上传失败");
    }

    @ApiOperation(value = "文件下载", notes = "文件下载")
    @GetMapping("/download/{id}")
    public void downloadFile(@PathVariable("id") Long id, HttpServletResponse response, HttpServletRequest request) throws IOException {
        com.smartfactory.sail.entity.File byId = iFileService.getById(id);
        String url = byId.getFileName();
        String filePath = FILEPATH + url;
        response.setCharacterEncoding(request.getCharacterEncoding());
        response.setContentType("application/octet-stream");
        FileInputStream fis = null;
        try {
            File file = new File(filePath);
            fis = new FileInputStream(file);
            response.setHeader("Content-Disposition", "attachment; filename=" + file.getName());
            IOUtils.copy(fis, response.getOutputStream());
            response.flushBuffer();
        } finally {
            if (fis != null) {
                try {
                    fis.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }

    @ApiOperation(value = "生成二维码", notes = "传入字符串生成二维码")
    @GetMapping("createCode/{value}")
    public void create(@PathVariable("value") String value, HttpServletResponse response) throws Exception {
        BufferedImage image = ZXingCode.createImage(value, value);

        //BufferedImage 转 InputStream
        ByteArrayOutputStream byteArrayOutputStream = new ByteArrayOutputStream();
        ImageOutputStream imageOutput = ImageIO.createImageOutputStream(byteArrayOutputStream);
        ImageIO.write(image, "png", imageOutput);
        InputStream inputStream = new ByteArrayInputStream(byteArrayOutputStream.toByteArray());
        long length = imageOutput.length();

        //设置response
        response.setContentType("application/force-download");

        response.setContentLength((int) length);
        response.setHeader("Content-Disposition", "attachment;filename=" + new String((value + "-二维码").getBytes("UTF-8"), "ISO-8859-1") + ".png");

        //输出流
        byte[] bytes = new byte[1024];
        OutputStream outputStream = response.getOutputStream();
        long count = 0;
        while (count < length) {
            int len = inputStream.read(bytes, 0, 1024);
            count += len;
            outputStream.write(bytes, 0, len);
        }
        outputStream.flush();
    }
}